const jwt = require("jsonwebtoken");

const secret = "123456";

// 生成 token
const getToken = (payload) => {
  const token = jwt.sign(payload, secret, { expiresIn: "24h" });
  return token;
};

// 生成短 token
const getShortToken = (payload) => {
  const shortToken = jwt.sign(payload, secret, { expiresIn: "1h" });
  return shortToken;
};

// 生成长 token
const getLongToken = (payload) => {
  const longToken = jwt.sign(payload, secret, { expiresIn: "5h" });
  return longToken;
};

// 验证 token的中间件
const verifyToken = async (ctx, next) => {
  const token = ctx.headers.authorization; // 从 Authorization 头获取 token
  if (!token) {
    ctx.status = 401;
    ctx.body = {
      code: 401,
      message: "Token is required",
    };
  }

  try {
    const decoded = jwt.verify(token, secret);
    // 将解码后的用户信息存入 ctx.state 中
    ctx.state.user = decoded;
    ctx.req.user = decoded;

    return next();
  } catch (error) {
    ctx.status = 401;
    ctx.body = {
      code: 401,
      message: "Token is invalid or expired",
    };
    return;
  }
};

// 解码 token
const decodeToken = (token) => {
  return jwt.decode();
};

module.exports = {
  getToken,
  verifyToken,
  getLongToken,
  getShortToken,
};
